package netty.rpc.framework.core.netty.transport.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import netty.rpc.framework.core.netty.transport.protocol.RPCMessage;
import netty.rpc.framework.core.netty.transport.serializer.Serializer;
import netty.rpc.framework.core.netty.transport.serializer.impl.DefaultSerializer;
import netty.rpc.framework.core.netty.transport.serializer.impl.KryoSerializer;


/**
 * @author guiyiqiao
 * @date 2020/12/3
 *
 * Netty 的编码器，将 RPCMessage 数据解码为 byte 数据
 */
@Slf4j
public class RPCMessage2ByteEncoder extends MessageToByteEncoder<RPCMessage> {

    private Serializer serializer = new KryoSerializer();
    /**
     * 使用于发送RPCMessage消息编码
     * @param channelHandlerContext
     * @param rpcMessage
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RPCMessage rpcMessage, ByteBuf byteBuf) throws Exception {

        log.info("to {} rpcMessage = {}",channelHandlerContext.channel().remoteAddress().toString(),rpcMessage.toString());
        int len = 0;

        byte[] serialize = serializer.serialize(rpcMessage);
        len += serialize.length;
        byteBuf.writeInt(len);
        byteBuf.writeBytes(serialize);

        log.info("len = {}",len);
    }

}